package cn.kgm.server;

import cn.kgm.handler.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

/**
 * @author kappi
 * @kapi #技术改变自己#
 * @PACKAGE: cn.kgm.server.IM
 * @EMAIL: Yolo.jk@qq.com
 * @DATE: 2023/4/16 15:53
 * @DAY_NAME_SHORT: 周日
 */
public class IMServer {
    private static Logger log = Logger.getLogger("IMServer");

    public static final Map<String, Channel> USERS = new ConcurrentHashMap<>(1024);

    public static void start() throws InterruptedException {
        // 创建线程池
        EventLoopGroup boss = new NioEventLoopGroup();
        // 创建工作线程池
        EventLoopGroup worker = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        // 添加http编码解析器
                        pipeline.addLast(new HttpServerCodec())
                                // 添加对大数据支持
                                .addLast(new ChunkedWriteHandler())
                                // 添加聚合操作
                                .addLast(new HttpObjectAggregator(1024 * 64))
                                // 添加WebSocket
                                .addLast(new WebSocketServerProtocolHandler("/"))
                                // 添加接受WebSocket信息的解析器
                                .addLast(new WebSocketHandler());
                    }
                });

        // 绑定端口号
        bootstrap.bind(8080).sync();
        log.info("netty server start success.");
    }
}
